package com.cloud.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.loadbalancer.LoadBalancerClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

@RestController
public class WebController {
    @Autowired
    private RestTemplate restTemplate;

//    @GetMapping("hello/{name}")
//    public String hello(@PathVariable("name") String name) {
//        return restTemplate.getForObject("http://localhost:10001/hello/"+name, String.class);
//    }

    @GetMapping("hello/{name}")
    public String hello(@PathVariable("name") String name) {
        // 访问路径的名称为 服务提供者的spring.application.name属性，即注册到Eureka的名称
        String serviceUri = "http://loadbalancer-provider";
        return restTemplate.getForObject(serviceUri + "/hello/" + name, String.class);
    }


    @Autowired
    private LoadBalancerClient loadBalancerClient;

    @GetMapping("load-balance")
    public String loadBalance() {
        ServiceInstance instance = loadBalancerClient.choose("loadbalancer-provider");
        return instance.getHost() + ":" + instance.getPort();
    }
}
